import React, {useState, useEffect} from "react";
import { ScrollView, Button, View, Text, StyleSheet } from 'react-native';
import { NavigationContainer, ParamListBase } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { Tester, TestSuite, TestCase } from '@rnoh/testerino';
import { enableFreeze, enableScreens, freezeEnabled } from 'react-native-screens';
import { NativeStackNavigationProp } from 'react-native-screens/native-stack';

// 全局设置
enableScreens(false);
enableFreeze(true);
console.log("Freeze enabled: " + freezeEnabled());

export const ScreensTest = () => {
  // 添加状态管理
  const [screensEnabled, setScreensEnabled] = useState(false);
  const [freezeEnabledState, setFreezeEnabledState] = useState(true);
  const [counter, setCounter] = useState(0);
  
  // 计数器效果
  useEffect(() => {
    const interval = setInterval(() => {
      setCounter(c => c + 1);
    }, 1000);
    
    return () => clearInterval(interval);
  }, []);
  
  // 同步状态显示
  useEffect(() => {
    // 更新全局状态
    enableScreens(screensEnabled);
    enableFreeze(freezeEnabledState);
    
    console.log(`Screens enabled: ${screensEnabled}, Freeze enabled: ${freezeEnabledState}`);
  }, [screensEnabled, freezeEnabledState]);

  function Home({ navigation, }: { navigation: NativeStackNavigationProp<ParamListBase> }) {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <View>
          <Text>Home Screen</Text>
          <Text>计数器: {counter}</Text>
          <Button title="To TabScreen" onPress={() => navigation.push('TabScreen')} />
        </View>
      </View>
    );
  }
  
  const Tab = createBottomTabNavigator();
  const TabScreen = () => {
    return (
      <Tab.Navigator>
        <Tab.Screen name="toHome" component={Home} />
        <Tab.Screen name="toTabScreen" component={Inner} />
        <Tab.Screen name="toDetail" component={Detail} />
      </Tab.Navigator>
    );
  }
  
  function Detail({ navigation, }: { navigation: NativeStackNavigationProp<ParamListBase> }) {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>我是Details Screen</Text>
        <Button title="To Home" onPress={() => navigation.goBack()} />
      </View>
    );
  }
  
  const InnerStack = createStackNavigator();
  const Inner = () => (
    <InnerStack.Navigator>
      <InnerStack.Screen name="DeeperHome" component={Home} />
    </InnerStack.Navigator>
  );
  
  const Stack = createStackNavigator();
  
  // 切换 freeze 状态
  const toggleFreeze = () => {
    setFreezeEnabledState(!freezeEnabledState);
  };
  
  // 切换 screens 状态
  const toggleScreens = () => {
    setScreensEnabled(!screensEnabled);
  };

  return (
    <ScrollView>
      <View>
        <Tester style={{ paddingBottom: 80 }}>
          <TestSuite name={'Screens'}>
            {/* 原有测试用例1：保持不变 */}
            <TestCase itShould={'enableScreens(false):由于harmonyOS侧未实现原生化适配，所以需要设置为false禁用原生屏幕'}>
              <View style={styles.container}>
                <NavigationContainer>
                  <Stack.Navigator>
                    <Stack.Screen
                      name="Home"
                      component={Home}
                      options={{ title: '我是Home的title' }}
                    />
                    <Stack.Screen
                      name="TabScreen"
                      component={TabScreen}
                      options={{ title: '我是TabScreen的title' }}
                    />
                  </Stack.Navigator>
                </NavigationContainer>
              </View>
            </TestCase>
            
            {/* 原有测试用例2：保持不变 */}
            <TestCase itShould={'enableFreeze:防止React组件树的部分渲染,UI层无法看到效果'}>
              <View style={styles.container}>
                <View>
                  <Button 
                    title={freezeEnabledState ? '禁用 Freeze' : '启用 Freeze'} 
                    onPress={toggleFreeze}
                  />
                </View>
                <NavigationContainer>
                  <Stack.Navigator>
                    <Stack.Screen
                      name="Home"
                      component={Home}
                      options={{ title: '我是Home的title' }}
                    />
                    <Stack.Screen
                      name="TabScreen"
                      component={TabScreen}
                      options={{ title: '我是TabScreen的title' }}
                    />
                  </Stack.Navigator>
                </NavigationContainer>
              </View>
            </TestCase>
            
            {/* 原有测试用例3：保持不变 */}
            <TestCase itShould={'NativeStackNavigationProp:切换页面属性的封装，提供一种基于原生堆栈导航器的导航方式，无实际UI效果'}>
              <View style={styles.container}>
                <NavigationContainer>
                  <Stack.Navigator>
                    <Stack.Screen
                      name="Home"
                      component={Home}
                      options={{ title: '我是Home的title' }}
                    />
                    <Stack.Screen
                      name="TabScreen"
                      component={TabScreen}
                      options={{ title: '我是TabScreen的title' }}
                    />
                  </Stack.Navigator>
                </NavigationContainer>
              </View>
            </TestCase>
            
            {/* 新增测试用例1：enableScreens API 行为测试 */}
            <TestCase 
              itShould={'enableScreens API 行为测试'}
              tags={['C_API']}
              initialState={false}
              arrange={({ setState }) => (
                <View style={styles.container}>
                  <View style={styles.controlPanel}>
                    <Button
                      title={`${screensEnabled ? '禁用' : '启用'} Screens`}
                      onPress={() => {
                        toggleScreens();
                        setState(true);
                      }}
                      color={screensEnabled ? "#4caf50" : "#f44336"}
                    />
                    <Text style={styles.statusText}>Screens 状态: {screensEnabled ? '已启用' : '已禁用'}</Text>
                    <Text style={styles.infoText}>
                      {screensEnabled 
                        ? 'Screens 已启用，但 HarmonyOS 平台无原生支持' 
                        : 'Screens 已禁用，使用纯 JavaScript 实现'}
                    </Text>
                  </View>
                </View>
              )}
              assert={async ({ expect, state }) => {
                // API 调用正常
                expect(enableScreens).to.be.a('function');
                // 状态切换正常
                expect(state).to.be.true;
              }}
            />
            
            {/* 新增测试用例2：enableFreeze API 行为测试 */}
            <TestCase 
              itShould={'enableFreeze API 行为测试'}
              tags={['C_API']}
              initialState={false}
              arrange={({ setState }) => (
                <View style={styles.container}>
                  <View style={styles.controlPanel}>
                    <Button
                      title={`${freezeEnabledState ? '禁用' : '启用'} Freeze`}
                      onPress={() => {
                        toggleFreeze();
                        setState(true);
                      }}
                      color={freezeEnabledState ? "#4caf50" : "#f44336"}
                    />
                    <Text style={styles.statusText}>Freeze 状态: {freezeEnabledState ? '已启用' : '已禁用'}</Text>
                    <Text style={styles.infoText}>
                      {freezeEnabledState 
                        ? 'Freeze 已启用，但 HarmonyOS 平台无原生冻结效果' 
                        : 'Freeze 已禁用，后台组件保持活动'}
                    </Text>
                    <Text style={styles.infoText}>
                      计数器行为: {freezeEnabledState 
                        ? '应停止但实际继续' 
                        : '持续运行'}
                    </Text>
                  </View>
                </View>
              )}
              assert={async ({ expect, state }) => {
                // API 调用正常
                expect(freezeEnabled).to.be.a('function');
                // 状态切换正常
                expect(state).to.be.true;
              }}
            />
          </TestSuite>
        </Tester>
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    height: 500,
    overflow: 'hidden',
    backgroundColor: '#f9f9f9',
  },
  controlPanel: {
    padding: 16,
    backgroundColor: '#eef2ff',
    borderBottomWidth: 1,
    borderBottomColor: '#d6d9e0',
  },
  statusText: {
    marginTop: 10,
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
  },
  infoText: {
    marginTop: 5,
    fontSize: 14,
    color: '#666',
    lineHeight: 20,
  },
});

export const displayName = 'react-native-screens';
export const framework = 'React';
export const category = 'basic';
export const title = 'react-native-screens';
export const documentationURL = 'https://gitee.com/react-native-oh-library/usage-docs/blob/master/zh-cn/react-native-screens.md';
export const description = 'react-native-screens';

export const examples = [
  {
    title: 'react-native-screens',
    render: function (): any {
      return <ScreensTest />;
    },
  },
];